package com.kld.test;

import android.app.ActivityManager;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.Log;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 字符串工具类
 *
 * @author ocean
 * @date 2022-04-28
 */
public class StringUtils {


    private static final String SEP1 = "#";
    private static final String SEP2 = "|";
    private static final String SEP3 = "=";
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 3000;
    static String[] units = {"", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿", "万亿"};
    static char[] numArray = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};
    private static char[] m_hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    private static long lastClickTime;

    public static boolean isEmpty(String s) {
        return s == null || s.trim().length() == 0 || s.equals("null");
    }

    public static boolean isNotEmpty(String s) {
        return !isEmpty(s);
    }

    public static boolean isNotEmpty(Object s) {
        return s != null && !isEmpty(s.toString());
    }

    public static boolean isNotEmpty2(Object s) {
        return s != null && !isEmpty(s.toString());
    }

    public static boolean isStartWithHttp(String url) {
        return isNotEmpty(url) && url.startsWith("http://");
    }

    public static boolean isEqual(String a, String b) {
        if (a != null) {
            return a.equals(b);
        } else if (b != null) {
            return b.equals(a);
        } else {
            //            a==b==null
            return true;
        }
    }

    public static boolean isNotEqual(String a, String b) {
        return !isEqual(a, b);
    }

    // 判断是不是数字
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    // 判断是不是浮点数字
    public static boolean isDecimal(String str) {
        if (str == null || "".equals(str))
            return false;
        Pattern pattern = Pattern.compile("[0-9]*(\\.?)[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 判断是否有特殊字符
     *
     * @param s
     * @return false 包含有特殊字符 true 不包含特殊字符
     */
    public static boolean isSpecialString(String s) {
        String str = "^[a-zA-Z0-9_\u0391-\uFFE5]+$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(s);
        return m.matches();
    }

    // 计算字符的长度
    public static int length(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * g根据限定的长度获取字符串
     *
     * @param value       字符串
     * @param limitLength 限定的长度。 (字符长度，中文2，字母1）
     * @return
     */
    public static String getLimitStringlength(String value, int limitLength) {
        if (length(value) <= limitLength) {
            return value;
        }
        try {
            int valueLength = 0;
            String chinese = "[\u0391-\uFFE5]";
            /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
            for (int i = 0; i < value.length(); i++) {
                /* 获取一个字符 */
                String temp = value.substring(i, i + 1);
                /* 判断是否为中文字符 */
                if (temp.matches(chinese)) {
                    /* 中文字符长度为2 */
                    valueLength += 2;
                } else {
                    /* 其他字符长度为1 */
                    valueLength += 1;
                }
//                Loger.e("valueLength=" + valueLength);
                if (valueLength >= limitLength) {
                    return value.substring(0, i + 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value.substring(0, limitLength / 2);
    }

    /**
     * @return
     */
    public static String getWithFormat1(double money) {
        DecimalFormat decimalFormat = new DecimalFormat("##0.0");
        String format = "" + decimalFormat.format(money);
        //        SpannableString styledText = new SpannableString(format);
        //        return styledText;
        return format;
    }

    /**
     * @return
     */
    public static String getWithFormat2(double money) {
        DecimalFormat decimalFormat = new DecimalFormat("##0.00");
        String format = "" + decimalFormat.format(money);
        //        SpannableString styledText = new SpannableString(format);
        //        return styledText;
        return format;
    }

    /**
     * @return
     */
    public static double getWithFormatDouble2(double money) {
        DecimalFormat decimalFormat = new DecimalFormat("##0.00");
        String format = "" + decimalFormat.format(money);
        //        SpannableString styledText = new SpannableString(format);
        //        return styledText;
        return Double.valueOf(decimalFormat.format(money));
    }

    /**
     * @return
     */
    public static String getWithFormat3(double money) {
        DecimalFormat decimalFormat = new DecimalFormat("##0");
        String format = "" + decimalFormat.format(money);
        //        SpannableString styledText = new SpannableString(format);
        //        return styledText;
        return format;
    }

    /**
     * @return
     */
    public static int getWithFormatInt(double money) {
        DecimalFormat decimalFormat = new DecimalFormat("##0");
        String format = "" + decimalFormat.format(money);
        //        SpannableString styledText = new SpannableString(format);
        //        return styledText;
        return Integer.valueOf(format);
    }

    /**
     * @param num 钱
     * @return
     */
    public static String getJSWithFormat(double num) {
        DecimalFormat decimalFormat = new DecimalFormat("##0.000");
        String format = "" + decimalFormat.format(num);
        //        SpannableString styledText = new SpannableString(format);
        //        return styledText;
        return format;
    }

    /**
     * @param num 钱
     * @return
     */
    public static String getWithFormat(double num) {
        DecimalFormat decimalFormat = new DecimalFormat("##0.000000");
        String format = "" + decimalFormat.format(num);
        //        SpannableString styledText = new SpannableString(format);
        //        return styledText;
        return format;
    }

    /**
     * @param num 钱
     * @return
     */
    public static String getWithFormat3Or6(double num, String currenyUnit) {
        String format = getWithFormat(num);
        if (isNotEmpty(currenyUnit)) {
            if (currenyUnit.equals("JSJ")) {
                format = getJSWithFormat(num);
            }
        }
        return format;
    }

    /**
     * 判断URL是否可以访问
     */
    public static boolean isBooleURL(String url) {
        URL urlIntent;
        boolean isURL;
        try {
            urlIntent = new URL(url);
            InputStream in = urlIntent.openStream();

            isURL = true;
        } catch (Exception e1) {
            urlIntent = null;
            isURL = false;
        }
        return isURL;
    }

    /**
     * List转换String
     *
     * @param list :需要转换的List
     * @return String转换后的字符串
     */
    public static String ListToString(List<?> list) {
        StringBuffer sb = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) == null || list.get(i) == "") {
                    continue;
                }
                // 如果值是list类型则调用自己
                if (list.get(i) instanceof List) {
                    sb.append(ListToString((List<?>) list.get(i)));
                    sb.append(SEP1);
                } else if (list.get(i) instanceof Map) {
                    sb.append(MapToString((Map<?, ?>) list.get(i)));
                    sb.append(SEP1);
                } else {
                    sb.append(list.get(i));
                    sb.append(SEP1);
                }
            }
        }
        return "L" + sb.toString();
    }

    /**
     * Map转换String
     *
     * @param map :需要转换的Map
     * @return String转换后的字符串
     */
    public static String MapToString(Map<?, ?> map) {
        StringBuffer sb = new StringBuffer();
        // 遍历map
        for (Object obj : map.keySet()) {
            if (obj == null) {
                continue;
            }
            Object key = obj;
            Object value = map.get(key);
            if (value instanceof List<?>) {
                sb.append(key.toString() + SEP1 + ListToString((List<?>) value));
                sb.append(SEP2);
            } else if (value instanceof Map<?, ?>) {
                sb.append(key.toString() + SEP1
                        + MapToString((Map<?, ?>) value));
                sb.append(SEP2);
            } else {
                sb.append(key.toString() + SEP3 + value.toString());
                sb.append(SEP2);
            }
        }
        return "M" + sb.toString();
    }

    /**
     * String转换Map
     *
     * @param mapText :需要转换的字符串
     * @return Map<?
     */
    public static Map<String, Object> StringToMap(String mapText) {

        if (mapText == null || mapText.equals("")) {
            return null;
        }
        mapText = mapText.substring(1);

        mapText = mapText;

        Map<String, Object> map = new HashMap<String, Object>();
        String[] text = mapText.split("\\" + SEP2); // 转换为数组
        for (String str : text) {
            String[] keyText = str.split(SEP3); // 转换key与value的数组
            if (keyText.length < 1) {
                continue;
            }
            String key = keyText[0]; // key
            String value = keyText[1]; // value
            if (value.charAt(0) == 'M') {
                Map<?, ?> map1 = StringToMap(value);
                map.put(key, map1);
            } else if (value.charAt(0) == 'L') {
                List<?> list = StringToList(value);
                map.put(key, list);
            } else {
                map.put(key, value);
            }
        }
        return map;
    }

    /**
     * String转换List
     *
     * @param listText :需要转换的文本
     * @return List<?>
     */
    public static List<Object> StringToList(String listText) {
        if (listText == null || listText.equals("")) {
            return null;
        }
        listText = listText.substring(1);

        listText = listText;

        List<Object> list = new ArrayList<Object>();
        String[] text = listText.split(SEP1);
        for (String str : text) {
            if (str.charAt(0) == 'M') {
                Map<?, ?> map = StringToMap(str);
                list.add(map);
            } else if (str.charAt(0) == 'L') {
                List<?> lists = StringToList(str);
                list.add(lists);
            } else {
                list.add(str);
            }
        }
        return list;
    }

    /**
     * 将整数转换成汉字数字
     *
     * @param num 需要转换的数字
     * @return 转换后的汉字
     */
    public static String formatInteger(int num) {
        char[] val = String.valueOf(num).toCharArray();
        int len = val.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String m = val[i] + "";
            int n = Integer.valueOf(m);
            boolean isZero = n == 0;
            String unit = units[(len - 1) - i];
            if (isZero) {
                if ('0' == val[i - 1]) {
                    continue;
                } else {
                    sb.append(numArray[n]);
                }
            } else {
                sb.append(numArray[n]);
                sb.append(unit);
            }
        }
        return sb.toString();
    }

    /**
     * 将小数转换成汉字数字
     *
     * @param decimal 需要转换的数字
     * @return 转换后的汉字
     */
    public static String formatDecimal(double decimal) {
        String decimals = String.valueOf(decimal);
        int decIndex = decimals.indexOf(".");
        int integ = Integer.valueOf(decimals.substring(0, decIndex));
        int dec = Integer.valueOf(decimals.substring(decIndex + 1));
        String result = formatInteger(integ) + "." + formatFractionalPart(dec);
        return result;
    }

    /**
     * 格式化小数部分的数字
     *
     * @param decimal 需要转换的数字
     * @return 转换后的汉字
     */
    public static String formatFractionalPart(int decimal) {
        char[] val = String.valueOf(decimal).toCharArray();
        int len = val.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            int n = Integer.valueOf(val[i] + "");
            sb.append(numArray[n]);
        }
        return sb.toString();
    }

    /***
     * 获取url key,value;
     * @param url
     * @return
     */
    public static Map<String, String> getKeyValue(String url) {
        HashMap<String, String> map = new HashMap<String, String>();
        try {
            String arg = url.substring(url.indexOf("?") + 1, url.length());
            String[] strs = arg.split("&");
            for (int x = 0; x < strs.length; x++) {
                String[] strs2 = strs[x].split("=");
                if (strs2.length == 2) {
//                    System.out.println(strs2[0] + "  " + strs2[1]);
                    map.put(strs2[0], strs2[1]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public static String isNumberString(String number) {
        String numbers = "";
        if (number.equals("1")) {
            numbers = "一";
        } else if (number.equals("2")) {
            numbers = "二";
        } else if (number.equals("3")) {
            numbers = "三";
        } else if (number.equals("4")) {
            numbers = "四";
        } else if (number.equals("5")) {
            numbers = "五";
        } else if (number.equals("6")) {
            numbers = "六";
        } else if (number.equals("7")) {
            numbers = "日";
        }
        return numbers;
    }

    /**
     * APP是否在线
     *
     * @param context
     * @return
     */
    public static boolean stackResumed(Context context) {
        ActivityManager manager = (ActivityManager) context
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        List<ActivityManager.RunningTaskInfo> recentTaskInfos = manager.getRunningTasks(1);
        if (recentTaskInfos != null && recentTaskInfos.size() > 0) {
            ActivityManager.RunningTaskInfo taskInfo = recentTaskInfos.get(0);
            if (taskInfo.baseActivity.getPackageName().equals(packageName) && taskInfo.numActivities > 1) {
                return true;
            }
        }

        return false;
    }

    public static void CopyToClipboard(Context context, String text) {
        ClipboardManager clip = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        //clip.getText(); // 粘贴
        clip.setText(text); // 复制
    }


    // 判断是否符合身份证号码的规范
    public static boolean isIDCard(String IDCard) {
        if (IDCard != null) {
            String IDCardRegex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x|Y|y)$)";
            return IDCard.matches(IDCardRegex);
        }
        return false;
    }

    // 判断是否6-32位，包含数字、字母或符号
    public static boolean isPw(String pw) {
        if (pw.length() < 6 || pw.length() > 32) {
            return false;
        }
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(pw);
        if (m.find()) {
            return false;
        }
        return true;
    }


    public static String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        return format.format(date);
    }

    public static String getRepeatType(String repeatStr) {
        String str = "";
        switch (repeatStr) {
            case "NONE":
                str = "不重复";
//                str = "";
                break;
            case "DAY":
                str = "每天";
                break;
            case "WEEK":
                str = "每周";
                break;
            case "MONTH":
                str = "每月";
                break;
            case "YEAR":
                str = "每年";
                break;
            case "WORKINGDAY":
                str = "法定工作日";
                break;
            case "LUNARMONTH":
                str = "农历每月";
                break;
            case "LUNARYEAR":
                str = "农历每年";
                break;
        }

        return str;
    }

    public static Object copyByName(Object src, Object target) {
        if (src == null) {
            return null;
        }
        try {
            Map<String, Field> srcFieldMap = getAssignableFieldsMap(src);
            Map<String, Field> targetFieldMap = getAssignableFieldsMap(target);
            for (String srcFieldName : srcFieldMap.keySet()) {
                Field srcField = srcFieldMap.get(srcFieldName);
                if (srcField == null) {
                    continue;
                }
                // 变量名需要相同
                if (!targetFieldMap.keySet().contains(srcFieldName)) {
                    continue;
                }
                Field targetField = targetFieldMap.get(srcFieldName);
                if (targetField == null) {
                    continue;
                }
                // 类型需要相同
                if (!srcField.getType().equals(targetField.getType())) {
                    continue;
                }

                targetField.set(target, srcField.get(src));
            }
        } catch (Exception e) {
            // 异常
        }
        return target;
    }

    private static Map<String, Field> getAssignableFieldsMap(Object obj) {
        if (obj == null) {
            return new HashMap<String, Field>();
        }
        Map<String, Field> fieldMap = new HashMap<String, Field>();
        for (Field field : obj.getClass().getDeclaredFields()) {
            // 过滤不需要拷贝的属性
            if (Modifier.isStatic(field.getModifiers())
                    || Modifier.isFinal(field.getModifiers())) {
                continue;
            }
            field.setAccessible(true);
            fieldMap.put(field.getName(), field);
        }
        return fieldMap;
    }

    /**
     * 判断版本更新
     *
     * @param localVersion 本地app 版本号
     * @param newVersion   最新版本号
     * @return true 需要更新 false 不用
     */
    public static boolean updateApp(String localVersion, String newVersion) {
        String[] localVersionArray = localVersion.split("\\.");
        String[] newVersionArray = newVersion.split("\\.");
        if (localVersionArray.length < newVersionArray.length) {
            int cha = newVersionArray.length - localVersionArray.length;
            for (int i = 0; i < cha; i++) {
                localVersion = localVersion + ".0";
            }
            localVersionArray = localVersion.split("\\.");
        }
        try {
            for (int i = 0; i < newVersionArray.length; i++) {
                int temp = Integer.parseInt(newVersionArray[i]);
                int compar = Integer.parseInt(localVersionArray[i]);
                if (temp > compar) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断版本更新
     *
     * @param localVersion 本地app 版本号
     * @param newVersion   最新版本号
     * @return true 需要更新 false 不用
     */
    public static boolean updateApp2(String localVersion, String newVersion) {
        String localVersionArray = localVersion.replace(".", "");
        String newVersionArray = newVersion.replace(".", "");
        int localV = Integer.valueOf(localVersionArray);
        int newV = Integer.valueOf(newVersionArray);
        if (localV >= newV) {
            return false;
        } else {
            return true;
        }

    }


    /**
     * @param targetStr 要处理的字符串
     * @description 切割字符串，将文本和img标签碎片化，如"ab<img>cd"转换为"ab"、"<img>"、"cd"
     */
    public static List<String> cutStringByImgTag(String targetStr) {
        List<String> splitTextList = new ArrayList<String>();
        if (isNotEmpty(targetStr)) {
            Pattern pattern = Pattern.compile("<img.*?src=\\\"(.*?)\\\".*?>");
            Matcher matcher = pattern.matcher(targetStr);
            int lastIndex = 0;
            while (matcher.find()) {
                if (matcher.start() > lastIndex) {
                    splitTextList.add(targetStr.substring(lastIndex, matcher.start()));
                }
                splitTextList.add(targetStr.substring(matcher.start(), matcher.end()));
                lastIndex = matcher.end();
            }
            if (lastIndex != targetStr.length()) {
                splitTextList.add(targetStr.substring(lastIndex, targetStr.length()));
            }
        }
        return splitTextList;
    }

    /**
     * 获取Video标签中的src值
     *
     * @param content
     * @return
     */
    public static String getVideoSrc(String content) {
        String str_src = null;
        //目前img标签标示有3种表达式
        //<<video controls="" src="http://vd2.bdstatic.com/mda-jghq8i1wv7fttqmc/hd/mda-jghq8i1wv7fttqmc.mp4"></video>
        //开始匹配content中的<video />标签
        Pattern p_img = Pattern.compile("<(video|VIDEO)(.*?)(/>|></video>|>)");
        Matcher m_img = p_img.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            while (result_img) {
                //获取到匹配的<video />标签中的内容
                String str_img = m_img.group(2);

                //开始匹配<video />标签中的src
                Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher m_src = p_src.matcher(str_img);
                if (m_src.find()) {
                    str_src = m_src.group(3);
                }
                //结束匹配<img />标签中的src

                //匹配content中是否存在下一个<video />标签，有则继续以上步骤匹配<video />标签中的src
                result_img = m_img.find();
            }
        }
        return str_src;
    }

    /**
     * 获取img标签中的src值
     *
     * @param content
     * @return
     */
    public static String getImgSrc(String content) {
        String str_src = null;
        //目前img标签标示有3种表达式
        //<img alt="" src="1.jpg"/>   <img alt="" src="1.jpg"></img>     <img alt="" src="1.jpg">
        //开始匹配content中的<img />标签
        Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
        Matcher m_img = p_img.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            while (result_img) {
                //获取到匹配的<img />标签中的内容
                String str_img = m_img.group(2);

                //开始匹配<img />标签中的src
                Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher m_src = p_src.matcher(str_img);
                if (m_src.find()) {
                    str_src = m_src.group(3);
                }
                //结束匹配<img />标签中的src

                //匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
                result_img = m_img.find();
            }
        }
        return str_src;
    }

    /**
     * 关键字高亮显示
     *
     * @param target 需要高亮的关键字
     * @param text   需要显示的文字
     * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
     * SpannableStringBuilder textString = TextUtilTools.highlight(item.getItemName(), KnowledgeActivity.searchKey);
     * vHolder.tv_itemName_search.setText(textString);
     */
    public static SpannableStringBuilder highlight(String text, String target) {
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        CharacterStyle span = null;

        Pattern p = Pattern.compile(target);
        Matcher m = p.matcher(text);
        while (m.find()) {
            span = new ForegroundColorSpan(Color.parseColor("#EE5C42"));// 需要重复！
            spannable.setSpan(span, m.start(), m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannable;
    }

    /**
     * 从html文本中提取图片地址，或者文本内容
     *
     * @param html       传入html文本
     * @param isGetImage true获取图片，false获取文本
     * @return
     */
    public static ArrayList<String> getTextFromHtml(String html, boolean isGetImage) {
        ArrayList<String> imageList = new ArrayList<>();
        ArrayList<String> textList = new ArrayList<>();
        //根据img标签分割出图片和字符串
        List<String> list = cutStringByImgTag(html);
        for (int i = 0; i < list.size(); i++) {
            String text = list.get(i);
            if (text.contains("<img") && text.contains("src=")) {
                //从img标签中获取图片地址
                String imagePath = getImgSrc(text);
                imageList.add(imagePath);
            } else {
                textList.add(text);
            }
        }
        //判断是获取图片还是文本
        if (isGetImage) {
            return imageList;
        } else {
            return textList;
        }
    }

    /**
     * 去掉无效0
     *
     * @param value
     * @return Sting
     */
    public static String formatDoubleInvalidZero(double value) {
        BigDecimal bd = new BigDecimal(String.valueOf(value));
        if (bd.doubleValue() != 0) {
            return bd.stripTrailingZeros().toPlainString();
        } else {
            return "0";
        }


    }

    /**
     * 去掉无效0
     *
     * @param value
     * @return Sting
     */
    public static String formatStringInvalidZero(String value) {
        BigDecimal bd = new BigDecimal(value);
        if (bd.doubleValue() != 0) {
            return bd.stripTrailingZeros().toPlainString();
        } else {
            return "0";
        }

    }


    /**
     * 字符串转换成byte数组
     *
     * @param _str
     * @return
     */
    public static final byte[] string2ByteArray(String _str) {
        if (_str == null) {
            return null;
        }

        return _str.getBytes();
    }

    /**
     * byte数组转换成16进制字符串
     *
     * @param _aby
     * @return
     */
    public static final String byteArray2StringHex(byte[] _aby) {
        if (_aby == null || _aby.length == 0) {
            return null;
        }

        int iLen = _aby.length;
        char[] achHex = new char[iLen * 2];
        for (int i = 0; i < iLen; i++) {
            int iVal = _aby[i] & 0xFF;
            achHex[i * 2] = m_hexArray[iVal >>> 4];
            achHex[i * 2 + 1] = m_hexArray[iVal & 0x0F];
        }
        return new String(achHex);
    }


}
